package com.example.springbootdemo.controller;

import com.example.springbootdemo.bean.UserBean;
import com.example.springbootdemo.dao.UserRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class HelloController {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Value("${spring.datasource.url}")
    private String mysqlconnect;

    //http://localhost:8080/hello
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index() {

        String sql = "select  username from users where id = ?"; //limit 1
        String value = (String) jdbcTemplate.queryForObject(
                sql, new Object[]{1}, String.class);

        return "Hello " + value + mysqlconnect;
    }

    //http://localhost:8080/getMapById?id=1
    @RequestMapping(value = "/getMapById", method = RequestMethod.GET)
    public Map<String, Object> getMapById(Integer id) {
        String sql = "SELECT * FROM users WHERE ID = ?";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql, id);
        return map;
    }

    //http://localhost:8080/getMapById?id=1
    @RequestMapping(value = "/getUserById", method = RequestMethod.GET)
    public UserBean getUserById(Integer id) {
        String sql = "SELECT * FROM users WHERE ID = ?";
        UserBean user = jdbcTemplate.queryForObject(sql, new UserRowMapper(), new Object[]{id});
        return user;
    }
}
